$(function(){
	 // queryAllData();
     sLevelClick();
});

// 二级列表点击
function sLevelClick(){
	// $('.first-level li.select li').click(function(){
    var types=localStorage.getItem("cropName").split(",");
	var typeData=getTypeData(types);;
		name = "";
		$('.typeList').empty();
		var fLevel = $('.first-level li.select div').text();
		var sLevel = $(this).text();
		// $('.now').text(fLevel + ' > ' + sLevel);
        // $('.now').text("小麦");
		$(this).addClass('sel').siblings().removeClass('sel');
		for(var j = 0; j < typeData.length; j++){
			$('.typeList').append('<li>'+ typeData[j].producttype +'');
		}
		typeClick();
	// });
	if(name){
		slClick(name);
	}else{
		$('.first-level li.select li:nth(0)').click();
	}
}

// 类型点击
function typeClick(){
	$('.typeList li').click(function(){
        var types=localStorage.getItem("cropName").split(",");
        var typeData=getTypeData(types);
		third = '';
		$(this).addClass('select').siblings().removeClass('select');
		var type = $(this).text();
        $('.now').text(type);
		for(var i = 0; i < typeData.length; i++){
			if(type == typeData[i].producttype){
                queryFolder(typeData[i].typePinYin);
			}
			// if(type == typeData[i].producttype){//动态
			// 	var area = typeData[i].areapinyin;
			// 	var folder = typeData[i].folder;
			// 	var imgFolder = area + folder;
			// 	imgFolder = imgFolder.replace(/\\/g, '\/');
			// 	queryFolder(imgFolder);
			// }
		}
	});
	if(third){
		thClick(third);
	}else{
		$('.typeList li:nth(0)').click();
	}
}
//类型区别返回的类型值
function getTypeData(types) {
    var typeData;
    if(types[0]=="YuBao" && types[1]=="XiaoMai"){
        typeData=YuBaoXiaoMaiTypeData;
    }else if(types[0]=="YuBao" && types[1]=="YuMi"){
        typeData=YuBaoYuMiTypeData;
    }else if(types[0]=="ZaiHai" && types[1]=="XiaoMai"){
        typeData=ZaiHaiXiaoMaiTypeData;
    }else if(types[0]=="Apple" && types[1]=="shengyuqi"){
        typeData=YuBaoPingGuoShengYuQiTypeData;
    }else if(types[0]=="Apple" && types[1]=="nongshi"){
        typeData=YuBaoPingGuoNongShiTypeData;
    }else if(types[0]=="Apple" && types[1]=="qixiangzaihai"){
        typeData=YuBaoPingGuoQiXiangZaiHaiTypeData;
    }else if(types[0]=="YuBao" && types[1]=="YingTao"){
        typeData= YuBaoYingTaoTypeData;
	}else if(types[0]=="YuBao" && types[1]=="ChaYe"){
        typeData= YuBaoChaYeTypeData;
	}
    return typeData;
}
// 日期的相加减
function dateOperator(date, days, operator) {
    date = date.replace(/-/g, "/"); //更改日期格式
    var nd = new Date(date);
    nd = nd.valueOf();
    if (operator == "+") {
        nd = nd + days * 24 * 60 * 60 * 1000;
    } else if (operator == "-") {
        nd = nd - days * 24 * 60 * 60 * 1000;
    } else {
        return false;
    }
    nd = new Date(nd);

    var y = nd.getFullYear();
    var m = nd.getMonth() + 1;
    var d = nd.getDate();
    if (m <= 9) m = "0" + m;
    if (d <= 9) d = "0" + d;
    var cdate = y + "-" + m + "-" + d;
    return cdate;
//相减
//alert(dateOperator("2015-02-28", 1, "-"));
//相加
//alert(dateOperator("2015-02-28", 1, "+"));
}

// 显示图片
function showImg(imgs,typeName){
	$('.dataShow').empty();
	imgsArr = [];
	for(var i = 0; i < imgs.length; i++){
		var tempArr = imgs[i].split('\/');
		// var time = tempArr[tempArr.length - 1].split('_')[0];//小图名称
		if(typeName=="Apple"){
            var time = tempArr[tempArr.length - 1].split('_')[0];
            var shixiao = tempArr[tempArr.length - 1].split('_')[1];
            var times=time.substring(0,time.length-2);//20181208
			var t=times.substring(0,4)+"-"+times.substring(4,6)+"-"+times.substring(6,8)
            var imgName=dateOperator(t,shixiao/24,"+")
		}else{
            var time = tempArr[tempArr.length - 1].split('_')[6];
            var times=time.substring(0,time.length-4);
            var imgName=dateOperator("2019-01-14",times/24,"+")
		}
		imgsArr.push({
			time: imgName,
			path: imgs[i]
		});
	}
	if(0 == imgsArr.length){
		$('.dataShow').text('无数据');
	}
	var bigImgUrl = imgUrl + imgs[imgs.length - 1];
	$('.dataShow').append('<img id="qr_img" src="'+ bigImgUrl +'" alt="" />');
	imgListAdd(imgsArr);
}

// 添加小图
function imgListAdd(arr){
	smallIndex = 0;
	nowGroup = 1;
	// ul移动到最前面
	$('.img_list').css({'left': '0px'});
	$('.img_list').empty();
	var ulLen = arr.length * 114;
	$('.img_list').css({'width': ulLen + 'px'});
	for(var i = 0; i < arr.length; i++){
		$('.img_list').append('<li><img src="'+ arr[i].path +'" alt="" /><p>'+ arr[i].time +'</p></li>');
	}
	smallClick();
	// 显示的长度
	// var showLen = $('.content').width(); 
	// 小图总数
	var allNum = imgsArr.length;
	// 每组小图数量为8张
	// var showNum = 8;
	// 多少组
	allGroup = Math.ceil(allNum / showNum);
}

// 点击小图
function smallClick(){
	$('.img_list li').click(function(){
		$('.img_list li').removeClass('actived');
		$(this).addClass('actived');
		smallIndex = $(this).index();
		var url = $(this).find('img').attr('src');
		$('.dataShow img').attr('src', url);
		// $('.downLoad a').attr('href', url);
		$('.downLoad a').attr('download', url);
	});
	$('.img_list li:nth(0)').click();
}

// 第一张
$('.dataOpt .the-first').click(function(){
	smallIndex = 0;
	$('.img_list li').eq(smallIndex).click();
});
// 上一张
$('.dataOpt .last').click(function(){
	if(0 == smallIndex){
		return;
	}else{
		smallIndex--;
		$('.img_list li').eq(smallIndex).click();
	}
});
// 播放 每过1.5s点击下一张
$('.dataOpt .play').click(function(){
	clearInterval(timer1);
	if(0 == smallIndex){
		return;
	}else{
		$(this).hide();
		$('.dataOpt .pause').show();
		timer1 = setInterval(function(){
			if(0 == smallIndex){
				$('.dataOpt .pause').hide();
				$('.dataOpt .play').show();
				clearInterval(timer1);
			}else{
				// 播放下一张
				$('.dataOpt .last').click();	
			}
		}, 1500);
	}
});
// 暂停
$('.dataOpt .pause').click(function(){
	$(this).hide();
	$('.dataOpt .play').show();
	clearInterval(timer1);
});
// 下一张
$('.dataOpt .next').click(function(){
	if((imgsArr.length - 1) == smallIndex){
		return;
	}else{
		smallIndex++;
		$('.img_list li').eq(smallIndex).click();
	}
});
// 最后一张
$('.dataOpt .the-last').click(function(){
	smallIndex = imgsArr.length - 1;
	$('.img_list li').eq(smallIndex).click();
});
// 大图盒子第一张
$('.img_topbar .the-first').click(function(){
	$('.dataOpt .the-first').click();
	var url = $('.dataShow img').attr('src');
	$('.img_big').attr('src', url);
});
// 大图盒子上一张
$('.img_topbar .last').click(function(){
	$('.dataOpt .last').click();
	var url = $('.dataShow img').attr('src');
	$('.img_big').attr('src', url);
});
// 大图播放
$('.img_topbar .play').click(function(){
	clearInterval(timer2);
	if(0 == smallIndex){
		return;
	}else{
		$(this).hide();
		$('.img_topbar .pause').show();
		timer2 = setInterval(function(){
			if(0 == smallIndex){ // 如果是第一张
				$('.img_topbar .pause').hide();
				$('.img_topbar .play').show();
				clearInterval(timer2);
			}else{
				$('.img_topbar .last').click();
			}
		}, 1500);
	}
});
// 大图暂停
$('.img_topbar .pause').click(function(){
	$(this).hide();
	$('.img_topbar .play').show();
	clearInterval(timer2);
});
// 大图盒子下一张
$('.img_topbar .next').click(function(){
	$('.dataOpt .next').click();
	var url = $('.dataShow img').attr('src');
	$('.img_big').attr('src', url);
});
// 大图盒子最后一张
$('.img_topbar .the-last').click(function(){
	$('.dataOpt .the-last').click();
	var url = $('.dataShow img').attr('src');
	$('.img_big').attr('src', url);
});

// 上一页
$('.lastPage').click(function(){
	if(1 == nowGroup){
		return;
	}else{
		nowGroup--;
		var ulLeft = -(nowGroup - 1) * showNum * 114;
		animate($('.img_list')[0], ulLeft);
		// $('.img_list').css({'left': ulLeft});
	}
});
// 下一页
$('.nextPage').click(function(){
	if(nowGroup == allGroup){
		return;
	}else{
		nowGroup++;
		var ulLeft = -(nowGroup - 1) * showNum * 114;
		animate($('.img_list')[0], ulLeft);
		// $('.img_list').css({'left': ulLeft});
	}
});

// 放大图片
$('.bigIt').click(function(){
	clearInterval(timer1);
	$('.dataOpt .pause').hide();
	$('.dataOpt .play').show();
	$('.musk').show();
	$('.imgBox').show();
	var leftDis = ($(window).width() - $('.imgBox').width()) / 2 + 'px';
	var topDis = ($(window).height() - $('.imgBox').height()) / 2 + 'px';
	$('.imgBox').css({'top': topDis, 'left': leftDis});
	var src = $('.dataShow > img').attr('src');
	$('.img_big').attr('src', src);
	var viewHeight = $('.imgBox').height() - 36;
	$('.img_view').css({'height': viewHeight + 'px'});
	moveImg();
});

// 关闭放大的图片
$('.imgClose').click(function(){
	clearInterval(timer2);
	$('.musk').hide();
	$('.imgBox').hide();
	$('.img_topbar .pause').click();
});

// 图片移动
function moveImg(){
	var viewImg = document.getElementsByClassName('img_view')[0]; // 盒子
	var bigImg = document.getElementsByClassName('img_big')[0];   // 图片
	bigImg.onmousedown = function(){
	    //鼠标在页面中的位置 - 盒子在页面中的位置 - 图片在盒子中的位置
	    var event = event || window.event;
	    event.preventDefault();
	    var pageX = event.pageX || client.pageX + document.documentElement.scrollLeft;
	    var pageY = event.pageY || client.pageY + document.documentElement.scrollTop;

	    //鼠标在图片中的位置是:
	    var boxX = pageX - viewImg.offsetLeft - bigImg.offsetLeft;
	    var boxY = pageY - viewImg.offsetTop - bigImg.offsetTop;

	    document.onmousemove = function (event) {
	        //获取鼠标位置
	        var event = event || window.event;
	        var pageX = event.pageX || client.pageX + document.documentElement.scrollLeft;
	        var pageY = event.pageY || client.pageY + document.documentElement.scrollTop;

	        //设置盒子位置(鼠标的位置给盒子的位置)
	        bigImg.style.left = pageX - viewImg.offsetLeft - boxX + "px";
	        bigImg.style.top = pageY - viewImg.offsetTop - boxY + "px";

	        //防止当移动过快时“注册信息(可以拖拽)”会被选中
	        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
	    };
	        
		document.onmouseup = function () {
		    document.onmousemove = null;
		    document.onmouseup = null;
		};
	};
}

// 下载图片
$('.downLoad').click(function(){
    // var imgSrc=$(".dataShow").find('img').attr('src');
    //
    // var timestamp = (new Date()).getTime();
    // console.log(timestamp); //1495302061441
    // var name=timestamp+".png";
    // downloadIamge('#qr_img', name);
    // $('.downLoad > a').attr('href', "http://10.172.13.57:8087/data/Province/610000/YuBao/XiaoMai/ChouSuiQian/20181228/Province_610000_YuBao_XiaoMai_ChouSuiQian_20181228_072.png")
    // $('.downLoad > a').attr('download',"test.png")
    //图片路径
    var src =$(".dataShow").find('img').attr('src');
    //下载保存文件名
    var imgname = 'testImg.png';
    download(src,imgname);
});

function download(src,imgname) {
    $('#downImg').attr('src', src);
    var img = $('#downImg').attr("src");
    var alink = document.createElement("a");
    alink.href = img;
    alink.download = imgname;
    alink.click();
}



function downloadIamge(selector, name) {
    var image = new Image()
    // 解决跨域 Canvas 污染问题
    image.setAttribute('crossOrigin', 'anonymous')
    image.crossOrigin="anonymous";
    image.onload = function () {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height

        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png')

        // 生成一个a元素
        var a = document.createElement('a')
        // 创建一个单击事件
        var event = new MouseEvent('click')

        // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
        a.download = name || '下载图片名称'
        // 将生成的URL设置为a.href属性
        a.href = url

        // 触发a的单击事件
        a.dispatchEvent(event)
    }

    image.src = document.querySelector(selector).src
}

function getFrame(){
	//var title = $(window.frameElement).attr("title");
	//  var title = "2018年06月02吉林省旬降水量";
    var title = "抽穗后";
	if(title){
		for(var i = 0; i < allData.length; i++){
			var item = allData[i].children;
			for(var j = 0; j < item.length; j++){
				var typename = item[j].producttype;
				if(title.indexOf(typename) != -1){
					name = typename;
					type = allData[i].producttype;
					var thirdType = item[j].children;
					for(var k = 0; k < thirdType.length; k++){
						var thirdName = thirdType[k].producttype;
						if(title.indexOf(thirdName) != -1){
							third = thirdName;
						}
					}
					$(window.frameElement).attr("title", "");
					break;
				}
			}
		}
	}
}

function flClick(type){
	var fls = $(".first-level > li");
	for(var i = 0; i < fls.length; i++){
		var div = $(fls[i]).find("div").text();
		if(div == type){
			$(fls[i]).find("div").click();
		}
	}
}

function slClick(name){
	var sls = $('.first-level > li.select').find('.second-level > li');
	for(var i = 0; i < sls.length; i++){
		if(name == $(sls[i]).text()){
			$(sls[i]).click();
		}
	}
}

function thClick(third){
	var ths = $('.typeList li');
	for(var i = 0; i < ths.length; i++){
		if(third == $(ths[i]).text()){
			$(ths[i]).click();
		}
	}
}